package com.liruo.treasureattic.authserver.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liruo.treasureattic.authserver.model.Oauth2TokenDTO;
import com.liruo.treasureattic.common.config.properties.JwtProperties;
import com.liruo.treasureattic.common.errhandler.exception.CommonResultException;
import com.liruo.treasureattic.common.errhandler.result.BaseResponse;
import com.liruo.treasureattic.common.errhandler.result.CommonCode;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.KeyPair;
import java.security.Principal;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

/**
 * @Author:liruo
 * @Date:2022-10-09-16:07:16
 * @Desc
 */
@RestController
@RequestMapping("/auth")
@Slf4j
public class AuthenticationController {
    @Resource
    private TokenEndpoint tokenEndpoint;
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    private KeyPair keyPair;


    @Resource
    private ObjectMapper objectMapper;
    /**
     * Oauth2登录认证
     */
    @PostMapping(value = "/token")
    public BaseResponse<Oauth2TokenDTO> postAccessToken(
            Principal principal,
            @RequestParam Map<String, String> parameters
    ) throws HttpRequestMethodNotSupportedException, JsonProcessingException {
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint
                .postAccessToken(principal, parameters).getBody();
        Oauth2TokenDTO oauth2TokenDTO = new Oauth2TokenDTO();
        if(oAuth2AccessToken ==null){
            log.error("oAuth2AccessToken == null");
            throw new CommonResultException("oAuth2AccessToken == null",CommonCode.SYSTEM);
        }
        oauth2TokenDTO.setToken(oAuth2AccessToken.getValue());
        oauth2TokenDTO.setRefreshToken(oAuth2AccessToken.getRefreshToken().getValue());
        oauth2TokenDTO.setTokenPrefix(jwtProperties.getTokenPrefix());
        oauth2TokenDTO.setExpireTime(oAuth2AccessToken.getExpiresIn());
        log.info("oauth2TokenDTO = {}",oauth2TokenDTO);
        return BaseResponse.success(oauth2TokenDTO);
    }


}
